<template>

  <!-- el-upload -->
  <!-- action :必选参数，上传的地址
    show-file-list: 是否显示已上传文件列表
    on-success:文件上传成功时的钩子 -->
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
    :drag="true"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>

</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  //   data() {
  //     return {
  //       imageUrl: ''
  //     }
  //   },
  methods: {
    uploadImage(e) {
      console.log(e) // 上传的图片是e.file
      console.log(e.file)
      const cos = new COS({
        SecretId: 'AKID4zhBRirnVyCD0Zu1xfNs9XjiX9ZkhPrw',
        SecretKey: 'xhDUbVCftyrY3NXbVEpGVWK0UkmaFiCi'
      }) // 完成cos对象的初始化
      cos.putObject(
        {
          Bucket: 'web90-1318397310', // 存储桶名称
          Region: 'ap-nanjing', // 地域名称
          Key: e.file.name, // 文件名称
          StorageClass: 'STANDARD', // 固定值
          Body: e.file // 文件对象
        },
        (err, data) => {
          if (data.statusCode === 200 && data.Location) {
            console.log(data)
            // 拿到了腾讯云返回的地址
            // 通过input自定义事件将地址传出去
            this.$emit('input', 'http://' + data.Location) // 将地址返回了
          } else {
            this.$message.error(err.Message) // 上传失败提示消息
          }
        }
      )
    },
    handleAvatarSuccess(res, file) {
      //   this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload-dragger{
    width: 180px;
    height: 180px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
